import uploadFile from '../../../utils/ossutil/uploadFile';
import uploadConfig from '../../../utils/ossutil/config';
import dayjs from 'dayjs';
getApp().authPage.basePage({
    data: {
        paddingBottom: 0,
        show: false,
        options: [],
        fieldValue: '',
        cascaderValue: '',
        updateSuccessCount: 0,
        fileList1: [], //营业执照
        fileList2: [], // 公司图片
        introduce: [{
            label: "产品介绍",
            show: true,
            key: "projectCorporationDesc",
            id: 31232
        }, {
            label: "生意亮点",
            show: true,
            key: "projectBusinessHighlightDesc",
            id: 43254

        }, {
            label: "运营情况",
            show: true,
            key: "projectOperationSituationDesc",
            id: 5465
        }, {
            label: "其他信息",
            key: "projectOtherDesc",
            show: false,
            id: 94837589
        }],
        formData: {

        },
        cityName: "",
        project_industry: [], // 行业类型
        project_sell_reason: [], //出售原因
        project_type: [], // 身份
        project_user_type: [], //用户行业
        showReason: false, //出售原因弹窗
        showProfession: false, //行业 
        showIdentity: false, //企业身份
        showCity: false, //城市 
        typeList: {},
        TypeAndIndustry: "", //行业和类型
        //行业
        temp_projectIndustryLabel: "",
        temp_projectIndustryValue: "",
        // 类型
        temp_projectTypeLabel: "",
        temp_projectTypeValue: "",
        // 出售原因
        temp_projectSellReasonLabel: "",
        temp_projectSellReasonValue: "",
        // 身份
        temp_projectUserTypeLabel: "",
        temp_projectUserTypeValue: "",
        temp_cityList: [],
        cityCode: '',
        fieldNames: {
            text: 'name',
            value: 'code',
            children: 'children',
        },
        // 城市相关
        selectAllCityInfo: "",
        cityHistory: [], // 搜索城市历史 
        isSelectprovince: "", //选中省份 
        isSelectCity: "", //选中的城市
        isSelectDistrict: "", //选中的地区
        // 临时信息
        projectCityCode: "",
        projectCityName: "",
        projectProvinceCode: "",
        projectProvinceName: "",
        hostCity: [], //热门城市
        myCity: [], //定位城市
        myDistrict: [], //选中城市后返回的地区信息
        showCity: false,
    },
    onLoad(e) {
        this.citySearch('', "hostCity");
        if(e.id){
            this.getEditDetail(e.id);
        }else{
            wx.showModal({
              title: '错误',
              content: '无法检索ID,请返回。',
              showCancel:false,
              success(res){
                if(res.confirm){
                    wx.navigateBack();
                }
              }
            })
        }
    },
    // 获取线索详情
    getEditDetail(id) {
        var that = this;
        getApp().http.editDetail({
            projectId: id
        }).then(res => {
            if (res.errorCode === 200) {
                let dataList = getApp().utils.fieldsfiltrati(res.data, ['projectBusinessLicenseImages', 'projectCorporationImages', 'projectCollect']);
                console.log('dataList', dataList);
                that.setData({
                    formData: dataList,
                    isSelectCity: res.data.projectCityCode,
                    selectAllCityInfo: `${res.data.projectProvinceName}/${res.data.projectCityName}`,
                    TypeAndIndustry: `${res.data.projectTypeLabel}/${res.data.projectIndustryLabel}`,
                });
            }
        })
    },
    // 关闭城市弹窗
    onCityClose() {
        this.setData({
            showCity: false,
        })
    },
    // 请求城市接口信息
    citySearch(data, key) {
        let formData = {
            cityName: "hotCitys",
            cityCode: ""
        };
        if (data) {
            formData = data;
        }
        // 获取热门城市
        getApp().http.citySearch(formData).then(res => {
            if (res.errorCode === 200) {
                if (formData.cityName === "hotCitys") {
                    this.citySearch({
                        cityCode: res.data[0].cityCode,
                        cityName: "",
                    }, 'myDistrict');
                }
                this.setData({
                    [key]: res.data,
                    isSelectCity: res.data[0].cityCode,
                })
            }
        });
        // 获取当前城市信息 
    },
    // 筛选-确定选择
    confirmCitySelect() {
        var that = this;
        var {
            projectCityCode,
            projectCityName,
            projectProvinceCode,
            projectProvinceName
        } = this.data;
        this.setData({
            "formData.projectCityCode": projectCityCode,
            "formData.projectCityName": projectCityName,
            "formData.projectProvinceCode": projectProvinceCode,
            "formData.projectProvinceName": projectProvinceName,
            "showCity": false,
            "selectAllCityInfo": `${projectProvinceName}/${projectCityName}`
        });
    },
    // 筛选-清除选择
    ClearCitySelect() {
        this.setData({
            isSelectCity: "",
            isSelectDistrict: "",
            isSelectprovince: "",
            "formData.projectAreaCode": '',
            "formData.projectAreaName": '',
            "formData.projectCityCode": '',
            "formData.projectCityName": '',
            "formData.projectProvinceCode": '',
            "formData.projectProvinceName": ''
        })
    },
    goCitySearch() {
        this.setData({
            showCity: false,
        })
        wx.navigateTo({
            url: '/pages/citySearch/citySearch',
        })
    },
    // 筛选-点击城市
    screenCity(e) {
        var {
            item,
            index,
            key
        } = getApp().utils.getParameter(e);
        this.setData({
            [key]: item.cityCode,
            projectCityCode: item.cityCode,
            projectCityName: item.cityName,
            projectProvinceCode: item.provinceCode,
            projectProvinceName: item.provinceName,
            isSelectprovince: item.provinceCode,
        });
    },
    getFileSuffix(value, key) {
        let nameArray = value.split(key);
        if (nameArray.length != 0) {
            return nameArray[nameArray.length - 1];
        } else {
            return value;
        }
    },
    // 上传营业执照
    uploadFileList1(id) {
        var that = this;
        // 未上传列表
        let noUpload = [];
        var noUploadIndex = 0
        for (let i = 0; i < this.data.fileList1.length; i++) {
            let item = this.data.fileList1[i];
            if (item.upload === false) {
                noUpload.push(item);
                noUploadIndex = i;
            }
        }
        setTimeout(() => {
            // 未上传列表等于空的情况下表示上传完成，进行下一步
            if (noUpload.length === 0) {
                wx.showLoading({
                    title: '上传营业执照成功',
                })
                this.uploadFileList2(id);
            } else {
                // 截取尾缀
                let fileImageType = this.getFileSuffix(noUpload[0].url, ".");
                let timeFiles = dayjs(new Date()).format("YYYY/MM/DD");
                let fileName = `projectBusinessLicense/${timeFiles}/${new Date().getTime()}.${fileImageType}`
                uploadFile.uploadFile({
                    fileName: fileName,
                    filePath: noUpload[0].url,
                    failc: function (res) {
                        wx.showModal({
                            title: '上传失败',
                            content: "上传当前图片失败，请点击继续上传",
                            confirmText: "继续上传",
                            showCancel: false,
                            success() {
                                that.uploadFileList1();
                            }
                        })
                    },
                    successc: function (res) {
                        that.setData({
                            ['fileList1[' + noUploadIndex + '].upload']: true,
                        })
                        getApp().http.attachmentUpload({
                            "filePath": fileName,
                            "objType": 0,
                            "objId": id,
                            "fileSuffix": fileImageType,
                            "fileSize": noUpload[0].size,
                            "originalFileName": "", //原名称
                            "fileType": noUpload[0].fileType
                        }).then(res => {
                            that.uploadFileList1(id);
                        })
                    }
                })
            }
        }, 500)
    },
    // 上传公司照片
    uploadFileList2(id) {
        wx.hideLoading();
        var that = this;
        let noUpload = [];
        var noUploadIndex = 0
        for (let i = 0; i < this.data.fileList2.length; i++) {
            let item = this.data.fileList2[i];
            if (item.upload === false) {
                noUpload.push(item);
                noUploadIndex = i;
            }
        }
        if (noUpload.length === 0) {
            wx.showModal({
                title: '成功',
                content: '图片已上传成功，是否立即返回？',
            })
            return;
        } else {
            // 未上传列表等于空的情况下表示上传完成，进行下一步
            let fileImageType = this.getFileSuffix(noUpload[0].url, ".");
            let timeFiles = dayjs(new Date()).format("YYYY/MM/DD");
            let fileName = `projectCorporation/${timeFiles}/${new Date().getTime()}.${fileImageType}`
            uploadFile.uploadFile({
                fileName: fileName,
                filePath: noUpload[0].url,
                failc: function (res) {
                    wx.showModal({
                        title: '上传失败',
                        content: "上传当前图片失败，请点击继续上传",
                        confirmText: "继续上传",
                        success() {
                            that.uploadFileList2(id);
                        }
                    })
                },
                successc: function (res) {
                    that.setData({
                        ['fileList2[' + noUploadIndex + '].upload']: true,
                    })
                    getApp().http.attachmentUpload({
                        "filePath": fileName,
                        "objType": 1,
                        "objId": id,
                        "fileSuffix": fileImageType,
                        "fileSize": noUpload[0].size,
                        "originalFileName": "", //原名称
                        "fileType": noUpload[0].fileType
                    }).then(res => {
                        that.uploadFileList2(id);
                    })
                }
            })
        }
    },
    submitFormData() {
        wx.showLoading({
            title: '保存中...',
        })
        getApp().http.editSubmit({
            ...this.data.formData
        }).then(res => {
            wx.hideLoading();
            if (res.errorCode === 200) {
                wx.showModal({
                    title: '成功',
                    content: '编辑成功，是否立即返回？',
                    showCancel: false,
                    success(ref) {
                        if (ref.confirm) {
                            wx.navigateBack();
                        }
                    }
                })
            } else {
                wx.showToast({
                    title: '编辑失败，请重试。',
                })
            }
        })
    },
    async uploadFileAliyun(objId, objType, objTypeStr, file) {
        let fileImageType = this.getFileSuffix(file.url, ".");
        let timeFiles = dayjs(new Date()).format("YYYY/MM/DD");
        let fileName = `${objTypeStr}/${timeFiles}/${new Date().getTime()}.${fileImageType}`
        await uploadFile.uploadFile({
            fileName: fileName,
            filePath: file.url,
            successc: async (res) => {
                await getApp().http.attachmentUpload({
                    "filePath": fileName,
                    "objType": objType,
                    "objId": objId,
                    "fileSuffix": fileImageType,
                    "fileSize": file.size,
                    "fileType": file.fileType
                })
                const i = this.data.updateSuccessCount + 1
                this.setData({
                    updateSuccessCount: i
                })
                if (i == this.data.fileList1.length + this.data.fileList2.length) {
                    wx.hideLoading();
                    wx.showModal({
                        title: '成功',
                        content: '图片已上传成功，是否立即返回？',
                    })
                }
            }
        })
    },
    setInput(e) {
        let key = e.currentTarget.id;
        if (key) {
            this.setData({
                ['formData.' + key]: e.detail
            })
        }
    },
    // 清除用户选择
    clearItemSelects(e) {
        let saveData = {
            temp_projectIndustryLabel: "",
            temp_projectIndustryValue: "",
            temp_projectTypeLabel: "",
            temp_projectTypeValue: "",
        };
        this.setData(saveData)
    },
    onClickPopupItem(e) {
        let {
            index,
            item
        } = e.currentTarget.dataset;
        this.setData({
            [index + "Value"]: item.value,
            [index + "Label"]: item.label,
        })
    },
    // 确认
    onConfigPopupItem(e) {
        let {
            index
        } = e.currentTarget.dataset;
        if (this.data['temp_' + index + 'Value'] === "") {
            wx.showToast({
                title: '请至少选择一项确定',
                icon: "none",
            })
            return;
        }
        let saveData = {
            ['formData.' + index + 'Label']: this.data['temp_' + index + 'Label'],
            ['formData.' + index + 'Value']: this.data['temp_' + index + 'Value']
        };
        if (index === 'projectType') {
            // 判断行业
            if (this.data.temp_projectIndustryValue === "") {
                wx.showToast({
                    title: '请选择行业后继续',
                    icon: "none",
                })
                return;
            }
            if (this.data.temp_projectTypeValue === "") {
                wx.showToast({
                    title: '请选择类型后继续',
                    icon: "none",
                })
                return;
            }
            saveData['TypeAndIndustry'] = `${this.data.temp_projectTypeLabel},${this.data.temp_projectIndustryLabel}`
            saveData['formData.projectIndustryLabel'] = this.data.temp_projectIndustryLabel;
            saveData['formData.projectIndustryValue'] = this.data.temp_projectIndustryValue;
        }
        this.setData(saveData);
        this.closePopup();
    },
    // 获取字典信息
    dictTypeFun() {
        var that = this;
        getApp().http.dictTypeList({
            keys: ['project_industry', 'project_type', 'project_sell_reason', 'project_user_type']
        }).then(res => {
            if (res.errorCode === 200) {
                that.setData({
                    typeList: res.data
                })
            }
        }).catch(err => {
            console.log(err);
        })
    },
    onProfessionClose() {
        this.setData({
            showProfession: false,
        })
    },
    // 统一关闭所有弹窗
    closePopup(e) {
        this.setData({
            showReason: false,
            showProfession: false,
            showIdentity: false,
            showCity: false,
        })
    },
    openPopup(e) {
        var key = e.currentTarget.id;
        if (!key) {
            wx.showToast({
                title: '无法查找到ID',
            })
            return;
        }
        this.setData({
            [key]: true,
        })
    },
    setIntroduce(e) {
        const clickIndex = e.currentTarget.id
        let introduces = this.data.introduce;
        introduces[clickIndex].show = !introduces[clickIndex].show;
        this.setData({
            introduce: introduces
        });
    },
    // 设置城市信息
    setCityInfo(item) {
        var {
            cityCode,
            cityName,
            provinceCode,
            provinceName
        } = item;
        let dataItme = [item];
        this.setData({
            cityHistory: dataItme,
            projectCityCode: cityCode,
            projectCityName: cityName,
            projectProvinceCode: provinceCode,
            projectProvinceName: provinceName,
            isSelectprovince: provinceCode,
            "formData.projectCityCode": cityCode,
            "formData.projectCityName": cityName,
            "formData.projectProvinceCode": provinceCode,
            "formData.projectProvinceName": provinceName,
            "showCity": false,
            "selectAllCityInfo": `${provinceName}/${cityName}`
        })
        setTimeout(() => {
            this.setData({
                isSelectCity: cityCode,
            })
        }, 1500)
    },


    cityHistory() {
        var that = this;
        let selectCityItem = getApp().globalData.selectCityItem
        if (selectCityItem) {
            this.setCityInfo(selectCityItem);
            return;
        } else {
            wx.getStorage({
                key: "selectCityItem",
                success(res) {
                    setTimeout(() => {
                        that.setCityInfo(res.data);
                    }, 1000)
                }
            })
        }
    },
    //草稿赋值
    setFormDataValue() {
        var that = this;
        wx.getStorage({
            key: "ReleaseFormData",
            success(res) {
                that.setData({
                    formData: res.data,
                })
            }
        });
    },
    // 存为草稿
    savaFormData() {
        wx.setStorage({
            key: "ReleaseFormData",
            data: this.data.formData,
        });
    },
    onShow() {
        var that = this;
        this.dictTypeFun();
        // 获取城市搜索历史
        setTimeout(() => {
            that.setFormDataValue();
        }, 1200)
        this.cityHistory();
        this.setData({
            bottomHeight: getApp().globalData.view.iosSABottom + "px"
        })
    },
    onClick() {
        this.setData({
            show: true,
        });
    },
    afterReadFileList1(e) {
        var file = e.detail.file;
        file.upload = false;
        this.data.fileList1.push(file);
        this.setData({
            fileList1: this.data.fileList1
        })
    },
    afterReadFileList2(e) {
        var file = e.detail.file;
        file.upload = false;
        this.data.fileList2.push(file);
        this.setData({
            fileList2: this.data.fileList2
        })
    },
    delFileList1(e) {
        let imageIndex = e.detail.index;
        var temp_filter = this.data.fileList1;
        this.setData({
            fileList1: temp_filter.filter((item, index) => index !== imageIndex)
        })
    },
    delFileList2(e) {
        let imageIndex = e.detail.index;
        var temp_filter = this.data.fileList2;
        this.setData({
            fileList2: temp_filter.filter((item, index) => index !== imageIndex)
        })
    }
})